package com.wangy.net.http;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.text.NumberFormat;

public class DownloadThread extends Thread {

	private InputStream inputStream;
	private int contentLength;
	private String fileName;

	public DownloadThread(InputStream inputStream, int contentLength,
			String fileName) {
		this.inputStream = inputStream;
		this.contentLength = contentLength;
		this.fileName = fileName;
	}

	@Override
	public void run() {
		try {
			RandomAccessFile randomAccessFile = new RandomAccessFile(fileName,
					"rw");
			randomAccessFile.seek(0);
			randomAccessFile.setLength(contentLength);
			int count = 0;
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inputStream.read(buffer)) != -1) {
				randomAccessFile.write(buffer, 0, len);
				count = count + len;
			    System.out.println("download data "+count+" of "+contentLength+" "+percent(count, contentLength));
			}
			randomAccessFile.close();
			inputStream.close();
		} catch (FileNotFoundException e) {
			System.out.println("no resource is found to download...");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		super.run();
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public int getContentLength() {
		return contentLength;
	}

	public void setContentLength(int contentLength) {
		this.contentLength = contentLength;
	}

	private String percent(double p1, double p2) {
		String str;
		double p3 = p1 / p2;
		NumberFormat nf = NumberFormat.getPercentInstance();
		nf.setMinimumFractionDigits(2);
		str = nf.format(p3);
		return str;
	}
	
}
